<template>
  <view class="settings-container">
    <!-- 个人资料表单 -->
    <view class="form-section">
      <view class="form-title">
        <text class="title-text">{{ $t('settings.personal_info') }}</text>
      </view>
      
      <view class="form-content">
        <!-- 用户名（只读） -->
        <view class="form-item">
          <text class="label">{{ $t('settings.username') }}</text>
          <text class="readonly-field">{{ userInfo.username || $t('settings.not_set') }}</text>
        </view>
        
        <!-- 邮箱（只读） -->
        <view class="form-item">
          <text class="label">{{ $t('settings.email') }}</text>
          <text class="readonly-field">{{ userInfo.email || $t('settings.not_set') }}</text>
        </view>
        
        <!-- 真实姓名 -->
        <view class="form-item">
          <text class="label">{{ $t('settings.real_name') }}</text>
          <view class="name-fields">
            <input 
              class="name-input" 
              v-model="formData.first_name" 
              :placeholder="$t('settings.enter_first_name')"
              maxlength="10"
            />
            <input 
              class="name-input" 
              v-model="formData.last_name" 
              :placeholder="$t('settings.enter_last_name')"
              maxlength="10"
            />
          </view>
        </view>
        
        <!-- 出生日期 -->
        <view class="form-item">
          <text class="label">{{ $t('settings.birthday') }}</text>
          <picker mode="date" :value="formData.date_of_birth" @change="onDateChange">
            <view class="date-picker">
              <text class="date-text">{{ formData.date_of_birth || $t('settings.select_birthday') }}</text>
              <text class="calendar-icon">📅</text>
            </view>
          </picker>
        </view>
        
        <!-- 性别 -->
        <view class="form-item">
          <text class="label">{{ $t('settings.gender') }}</text>
          <picker :value="genderIndex" :range="genderOptions" @change="onGenderChange">
            <view class="picker-field">
              <text class="picker-text">{{ genderOptions[genderIndex] }}</text>
              <!-- <text class="arrow-icon">▼</text> -->
            </view>
          </picker>
        </view>
        
        <!-- 地址 -->
        <view class="form-item">
          <text class="label">{{ $t('settings.address') }}</text>
          <input 
            class="input-field" 
            v-model="formData.address" 
            :placeholder="$t('settings.enter_address')"
            maxlength="100"
          />
        </view>
        
        <!-- 医保机构 -->
        <view class="form-item">
          <text class="label">{{ $t('settings.medical_insurance') }}</text>
          <input 
            class="input-field" 
            v-model="formData.medical_insurance" 
            :placeholder="$t('settings.enter_medical_insurance')"
            maxlength="50"
          />
        </view>
        
        <!-- 职业 -->
        <view class="form-item">
          <text class="label">{{ $t('settings.profession') }}</text>
          <input 
            class="input-field" 
            v-model="formData.profession" 
            :placeholder="$t('settings.enter_profession')"
            maxlength="30"
          />
        </view>
        
        <!-- 联系电话 -->
        <view class="form-item">
          <text class="label">{{ $t('settings.mobile') }}</text>
          <input 
            class="input-field" 
            v-model="formData.mobile" 
            :placeholder="$t('settings.enter_mobile')"
            maxlength="20"
            type="number"
          />
        </view>
      </view>
      
      <!-- 保存按钮 -->
      <view class="form-actions">
        <button class="save-btn" @click="saveUserInfo" :disabled="saving">
          {{ saving ? $t('common.saving') : $t('common.save') }}
        </button>
      </view>
    </view>

  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@/store/user.js'
import { updateUserInfo } from '@/api/user.js'

const { t, locale } = useI18n()
const userStore = useUserStore()

// 响应式数据
const formData = ref({
  first_name: '',
  last_name: '',
  email: '',
  date_of_birth: '',
  gender: '',
  address: '',
  medical_insurance: '',
  profession: '',
  mobile: '' // 新增联系电话字段
})

const saving = ref(false)

// 性别选项
const genderOptions = computed(() => [
  t('settings.male'),
  t('settings.female')
])

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 性别索引 - 简单直接
const genderIndex = computed(() => {
  const gender = formData.value.gender
  // gender=1是男性，对应索引0；gender=0是女性，对应索引1
  // 如果gender为undefined/null，默认显示男性
  return gender === 1 ? 0 : 1
})
// 初始化表单数据
const initFormData = () => {
  const info = userInfo.value
  // console.log('初始化表单数据，用户信息:', info)
  
  formData.value = {
    first_name: info.first_name || '',
    last_name: info.last_name || '',
    email: info.email || '',
    date_of_birth: info.date_of_birth || '',
    gender: info.gender,
    address: info.address || '',
    medical_insurance: info.medical_insurance || '',
    profession: info.profession || '',
    mobile: info.mobile || '' // 初始化联系电话
  }
  
  // console.log('初始化后的表单数据:', formData.value)
  // console.log('性别索引:', genderIndex.value)
}

// 日期选择处理
const onDateChange = (e) => {
  formData.value.date_of_birth = e.detail.value
}

// 性别选择处理 - 简单直接
const onGenderChange = (e) => {
  const index = e.detail.value
  // console.log('*******性别选择处理，索引:', index)
  // 索引0是男性，索引1是女性
  formData.value.gender = index === 0 ? 1 : 0
}

// 保存用户信息
const saveUserInfo = async () => {
  // 验证表单
  if (!formData.value.first_name.trim() || !formData.value.last_name.trim()) {
    uni.showToast({
      title: t('settings.name_required'),
      icon: 'none'
    })
    return
  }
  
  // 验证出生日期
  if (formData.value.date_of_birth) {
    const dateObj = new Date(formData.value.date_of_birth)
    if (dateObj.toString() === 'Invalid Date') {
      uni.showToast({
        title: t('settings.invalid_date'),
        icon: 'none'
      })
      return
    }
    
    // 验证不能是未来日期
    const today = new Date()
    if (dateObj > today) {
      uni.showToast({
        title: locale.value === 'zh' ? '出生日期不能是未来日期' : 'Birth date cannot be in the future',
        icon: 'none'
      })
      return
    }
  }
  
  try {
    saving.value = true
    
    // 准备API请求数据，添加user_id，移除只读字段
    const apiData = {
      first_name: formData.value.first_name,
      last_name: formData.value.last_name,
      email: formData.value.email,
      date_of_birth: formData.value.date_of_birth,
      gender: formData.value.gender,
      address: formData.value.address,
      medical_insurance: formData.value.medical_insurance,
      profession: formData.value.profession,
      mobile: formData.value.mobile, // 添加联系电话到API数据
      user_id: userInfo.value.id || userInfo.value.user_id
    }
    // console.log('API请求数据:', apiData)
    
    // 调用API更新用户信息
    const response = await updateUserInfo(apiData)
    // console.log('API响应:', response)
    
    if (response.code === 200 || response.success) {
      // API调用成功，更新本地store
      await userStore.updateUserInfo(formData.value)
      
      uni.showToast({
        title: t('settings.update_success'),
        icon: 'success'
      })
    } else {
      throw new Error(response.message || '更新失败')
    }
    
  } catch (error) {
    console.error('保存用户信息失败:', error)
    uni.showToast({
      title: error.message || t('settings.update_failed'),
      icon: 'none'
    })
  } finally {
    saving.value = false
  }
}

// 页面显示时初始化数据
onShow(() => {
  // console.log('设置页面显示，初始化表单数据')
  initFormData()
})

// 页面加载时设置标题
onMounted(() => {
  uni.setNavigationBarTitle({
    title: t('settings.title')
  })
})
</script>

<style lang="scss" scoped>
.settings-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.form-title {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .title-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
}

.form-content {
  padding: 0 30rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f8f8f8;
  
  &:last-child {
    border-bottom: none;
  }
  
  .label {
    width: 160rpx;
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }
  
  .input-field {
    flex: 1;
    height: 60rpx;
    font-size: 28rpx;
    color: #333;
    background-color: #f8f9fa;
    border: 1rpx solid #e9ecef;
    border-radius: 8rpx;
    padding: 0 20rpx;
    outline: none;
    
    &::placeholder {
      color: #999;
    }
  }
  
  .readonly-field {
    flex: 1;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 28rpx;
    color: #333;
    background-color: transparent;
  }
  
  .name-fields {
    flex: 1;
    display: flex;
    gap: 20rpx;
    
    .name-input {
      flex: 1;
      height: 60rpx;
      font-size: 28rpx;
      color: #333;
      background-color: #f8f9fa;
      border: 1rpx solid #e9ecef;
      border-radius: 8rpx;
      padding: 0 20rpx;
      outline: none;
      
      &::placeholder {
        color: #999;
      }
    }
  }
  
  .date-picker,
  .picker-field {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 60rpx;
    padding: 0 20rpx;
    background-color: #f8f9fa;
    border-radius: 8rpx;
    border: 1rpx solid #e9ecef;
    
    .date-text,
    .picker-text {
      font-size: 28rpx;
      color: #333;
    }
    
    .calendar-icon,
    .arrow-icon {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.form-actions {
  padding: 40rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  
  .save-btn {
    width: 100%;
    height: 80rpx;
    background-color: #1296db;
    color: white;
    border: none;
    border-radius: 12rpx;
    font-size: 32rpx;
    font-weight: 600;
    
    &:disabled {
      background-color: #ccc;
    }
    
    &:active {
      background-color: #0f7bb8;
    }
  }
}

.other-settings {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f8f8f8;
  cursor: pointer;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:active {
    background-color: #f8f8f8;
  }
  
  .setting-label {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }
  
  .setting-value {
    display: flex;
    align-items: center;
    gap: 10rpx;
    
    .value-text {
      font-size: 28rpx;
      color: #666;
    }
    
    .arrow-icon {
      font-size: 24rpx;
      color: #999;
    }
  }
}
</style>
